<template>
    <div class="storage-management">
        <!-- 状态卡片 -->
        <a-card class="status-card" :bordered="true">
            <template #title>
                <div class="card-title">
                    <span>储存启用状态: {{ recordStatus }}</span>
                    <a-icon type="sync" :spin="isSpin" class="refresh-icon" @click="refreshStorageInfo" />
                </div>
            </template>            
            <div class="status-item">
                <span class="status-label">{{ recordStatus }}</span>
                <a-switch 
                    v-model="storageStatus"
                    :loading="isLoading"
                    :checked-children="'ON'"
                    :un-checked-children="'OFF'"
                    @change="toggleRecording"
                />
            </div>
        </a-card>

        <!-- SD卡管理卡片 -->
        <a-card class="sd-card-manager" :bordered="true">
            <template #title>
                <div class="card-title">
                    <span>SD卡状态: {{ statusText }}</span>
                    <a-icon type="sync" :spin="isRefreshing" class="refresh-icon" @click="refreshSdCardInfo" />
                </div>
            </template>
            
            <a-row :gutter="16">
                <!-- 容量信息 -->
                <a-col :span="12">
                    <div class="capacity-section">
                        <h4>容量</h4>
                        <div class="capacity-info">
                            <a-progress 
                                :percent="sdCardInfo.usedPercent" 
                                :status="getProgressStatus()"
                                :stroke-color="getProgressColor()"
                            />
                            <div class="capacity-details">
                                <p>{{ sdCardInfo.used.toFixed(1) }}GB / {{ sdCardInfo.total.toFixed(1) }}GB</p>
                                <p class="available-info">{{ sdCardInfo.available.toFixed(1) }}GB 可用</p>
                            </div>
                        </div>
                    </div>
                </a-col>

                <!-- 操作按钮 -->
                <a-col :span="12">
                    <div class="operations-section">
                        <h4>操作</h4>
                        <div class="operation-buttons">
                            <a-button 
                                type="primary" 
                                :disabled="!sdCardInfo.isConnected"
                                :loading="operationLoading.mount"
                                class="operation-btn"
                                @click="mountSdCard"
                            >
                                挂载
                            </a-button>
                            <a-button 
                                :disabled="!sdCardInfo.isMounted"
                                :loading="operationLoading.unmount"
                                class="operation-btn"
                                @click="unmountSdCard"
                            >
                                卸载
                            </a-button>
                            <a-button 
                                type="danger" 
                                :disabled="!sdCardInfo.isConnected"
                                :loading="operationLoading.format"
                                class="operation-btn format-btn"
                                @click="showFormatConfirm"
                            >
                                格式化
                            </a-button>
                        </div>
                    </div>
                </a-col>
            </a-row>
        </a-card>

        <!-- 存储管理配置卡片 -->
        <!-- <a-card title="存储管理" class="config-card" :bordered="true">
            <a-form :model="formData" :label-col="{span: 8}" :wrapper-col="{span: 16}">
                <a-form-item label="存储变量时间间隔">
                    <a-input-number 
                        v-model="formData.storageInterval"
                        :min="1"
                        :max="3600"
                        :precision="0"
                        style="width: 120px;"
                        @change="onStorageIntervalChange"
                    />
                    <span class="unit">秒</span>
                </a-form-item>

                <a-form-item label="数据库保存最长时间">
                    <a-input-number 
                        v-model="formData.maxStorageTime"
                        :min="1"
                        :max="365"
                        :precision="0"
                        style="width: 120px;"
                        @change="onMaxStorageTimeChange"
                    />
                    <span class="unit">天</span>
                </a-form-item>

                <a-form-item label="最大存储空间">
                    <a-input-number 
                        v-model="formData.maxStorageSpace"
                        :min="100"
                        :max="10240"
                        :precision="0"
                        style="width: 120px;"
                        @change="onMaxStorageSpaceChange"
                    />
                    <span class="unit">MB</span>
                </a-form-item>

                <a-form-item :wrapper-col="{offset: 8, span: 16}">
                    <a-button type="primary" @click="saveConfiguration">
                        保存
                    </a-button>
                </a-form-item>
            </a-form>
        </a-card> -->
    </div>
</template>

<script>
export default {
    name: 'StorageManagement',
    data() {
        return {
            // API配置
            host: '10.11.12.13:8888',
            TIMEOUT_MS: 3000,
            
            storageStatus: false, // 存储状态：false=已停止, true=启用
            formData: {
                storageInterval: 30,     // 存储变量时间间隔（秒）
                maxStorageTime: 30,      // 数据库保存最长时间（天）
                maxStorageSpace: 4096    // 最大存储空间（MB）
            },
            // SD卡相关数据
            isRefreshing: false,  // 刷新状态
            isLoading: false,     // 加载状态
            isSpin: false,        // 旋转加载状态
            recordStatus: '已停止', // 记录状态文本
            sdCardInfo: {
                isConnected: true,      // SD卡是否连接
                isMounted: false,       // SD卡是否已挂载
                total: 0,               // 总容量(GB) - 从API获取
                used: 0,                // 已使用(GB) - 计算得出
                available: 0,           // 可用空间(GB) - 从API获取
                availableCount: '0 可用 0 总量', // 可用数量显示
                usedPercent: 0,         // 使用百分比 - 从API获取
                status: ''             // SD卡状态 - 从API获取
            },
            operationLoading: {
                mount: false,    // 挂载操作加载状态
                unmount: false,  // 卸载操作加载状态
                format: false    // 格式化操作加载状态
            }
        }
    },
    computed: {
        // SD卡状态文本计算属性
        statusText() {
            if (this.sdCardInfo.status === '') return ''
            if (this.sdCardInfo.status === 'Ok') return '正常'
            if (this.sdCardInfo.status === 'fail') return '挂载失败'
            if (this.sdCardInfo.status === 'timeout') return '超时'
            return this.sdCardInfo.status
        },
        
        // 储存启用状态文本计算属性
        storageStatusText() {
            return this.storageStatus ? '启用' : '已停止'
        },
        
        // 根据百分比返回进度状态
        progressStatus() {
            if (this.sdCardInfo.usedPercent <= 60) {
                return 'success'
            } else if (this.sdCardInfo.usedPercent <= 90) {
                return 'warning'
            } else {
                return 'exception'
            }
        }
    },
    mounted() {
        this.loadStorageSettings()
        this.getStorageInfo() // 获取存储启用状态
        this.getSD() // 替换为真实的API调用
    },
    methods: {
        // 带超时的fetch工具方法
        fetchWithTimeout(resource, options = {}) {
            return Promise.race([
                fetch(resource, options),
                new Promise((_, reject) => 
                    setTimeout(() => reject(new Error('timeout')), this.TIMEOUT_MS)
                )
            ])
        },

        // 加载存储设置
        loadStorageSettings() {
            // 这里可以从API或本地存储加载配置
            console.log('加载存储管理配置')
        },

        // 存储间隔变更处理
        onStorageIntervalChange(value) {
            console.log('存储间隔变更:', value + '秒')
        },

        // 最大存储时间变更处理
        onMaxStorageTimeChange(value) {
            console.log('最大存储时间变更:', value + '天')
        },

        // 最大存储空间变更处理
        onMaxStorageSpaceChange(value) {
            console.log('最大存储空间变更:', value + 'MB')
        },

        // 保存配置
        saveConfiguration() {
            // 验证表单数据
            if (!this.validateForm()) {
                return
            }

            // 保存配置到后端或本地存储
            const config = {
                storageStatus: this.storageStatus,
                storageInterval: this.formData.storageInterval,
                maxStorageTime: this.formData.maxStorageTime,
                maxStorageSpace: this.formData.maxStorageSpace
            }

            console.log('保存存储管理配置:', config)
            
            // 这里可以调用API保存配置
            this.$message.success('配置保存成功!')
        },

        // 表单验证
        validateForm() {
            const { storageInterval, maxStorageTime, maxStorageSpace } = this.formData
            
            if (!storageInterval || storageInterval < 1 || storageInterval > 3600) {
                this.$message.error('存储间隔必须在1-3600秒之间')
                return false
            }
            
            if (!maxStorageTime || maxStorageTime < 1 || maxStorageTime > 365) {
                this.$message.error('最大存储时间必须在1-365天之间')
                return false
            }
            
            if (!maxStorageSpace || maxStorageSpace < 100 || maxStorageSpace > 10240) {
                this.$message.error('最大存储空间必须在100-10240MB之间')
                return false
            }
            
            return true
        },

        // SD卡相关方法
        // 获取SD卡信息
        async getSD() {
            this.isRefreshing = true
            try {
                const response = await this.fetchWithTimeout(`http://${this.host}/mgmt/sd/check`, {
                    method: 'POST'
                })
                const data = await response.json()
                
                // 更新SD卡信息
                this.sdCardInfo.usedPercent = data.msg.fsusePercent
                this.sdCardInfo.available = data.msg.fsavail
                this.sdCardInfo.total = data.msg.fssize
                this.sdCardInfo.status = data.msg.status
                
                // 计算已使用空间
                this.sdCardInfo.used = this.sdCardInfo.total - this.sdCardInfo.available
                
                // 更新连接和挂载状态
                this.sdCardInfo.isConnected = data.msg.status !== 'timeout'
                this.sdCardInfo.isMounted = data.msg.status === 'Ok'
                
                console.log('SD卡信息获取成功:', data)
                
            } catch (error) {
                console.log('获取SD卡信息失败:', error.message)
                this.sdCardInfo.status = 'timeout'
                this.sdCardInfo.isConnected = false
                this.sdCardInfo.isMounted = false
            } finally {
                this.isRefreshing = false
            }
        },

        // 刷新SD卡信息（保留现有方法名以兼容模板）
        async refreshSdCardInfo() {
            await this.getSD()
        },

        // 获取存储启用状态信息
        async getStorageInfo() {
            this.isSpin = true
            try {
                const response = await this.fetchWithTimeout(`http://${this.host}/v1/localHistoryRecord/fetchStatus`, {
                    method: 'GET'
                })
                const data = await response.json()
                if (data.code === 0) {
                    this.storageStatus = data.msg.status
                } else {
                    this.$message.error('获取状态失败: ' + (data.msg || '未知错误'))
                }
            } catch (error) {
                this.$message.error('请求超时或失败: ' + error.message)
            } finally {
                this.isLoading = false
                if (this.storageStatus) {
                    this.recordStatus = '正在记录'
                } else {
                    this.recordStatus = '已停止'
                }
                setTimeout(() => {
                    this.isSpin = false
                }, 500) // 保证旋转动画至少持续 500ms
            }
        },

        // 刷新存储启用状态
        async refreshStorageInfo() {
            await this.getStorageInfo()
        },

        // 状态切换处理
        async toggleRecording() {
            this.isLoading = true
            try {
                const response = await this.fetchWithTimeout(`http://${this.host}/v1/localHistoryRecord/toggleStatus`, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify({status: !this.storageStatus})
                })
                const data = await response.json()
                if (data.code === 0) {
                    this.storageStatus = data.msg.status
                    this.$message.success(data.msg.msg)
                } else {
                    this.$message.error('状态切换失败: ' + (data.msg || '未知错误'))
                }
            } catch (error) {
                this.$message.error('请求超时或失败: ' + error.message)
            } finally {
                console.log(this.storageStatus)
                this.isLoading = false
                if (this.storageStatus) {
                    this.recordStatus = '正在记录'
                } else {
                    this.recordStatus = '已停止'
                }
            }
        },

        // 获取进度条状态（兼容模板）
        getProgressStatus() {
            if (this.sdCardInfo.usedPercent <= 60) return 'success'
            if (this.sdCardInfo.usedPercent <= 90) return 'active'  
            return 'exception'
        },

        // 获取进度条颜色
        getProgressColor() {
            if (this.sdCardInfo.usedPercent <= 60) return '#52c41a'
            if (this.sdCardInfo.usedPercent <= 90) return '#faad14'
            return '#ff4d4f'
        },

        // 挂载SD卡
        async mountSdCard() {
            if (!this.sdCardInfo.isConnected) {
                this.$message.error('SD卡未连接')
                return
            }

            this.operationLoading.mount = true
            try {
                const response = await this.fetchWithTimeout(`http://${this.host}/mgmt/sd/mount`, {
                    method: 'POST'
                })
                const data = await response.json()
                
                if (data.code === 0) {
                    this.$message.success('挂载成功')
                    await this.getSD() // 更新SD卡状态
                } else {
                    this.$message.error('挂载失败: ' + (data.msg || '未知错误'))
                }
            } catch (error) {
                console.log('挂载操作异常:', error.message)
                this.$message.error('挂载操作失败')
            } finally {
                this.operationLoading.mount = false
            }
        },

        // 卸载SD卡
        async unmountSdCard() {
            if (!this.sdCardInfo.isMounted) {
                this.$message.error('SD卡未挂载')
                return
            }

            this.operationLoading.unmount = true
            try {
                const response = await this.fetchWithTimeout(`http://${this.host}/mgmt/sd/umount`, {
                    method: 'POST'
                })
                const data = await response.json()
                
                if (data.code === 0) {
                    this.$message.success('卸载成功')
                    await this.getSD() // 更新SD卡状态
                } else {
                    this.$message.error('卸载失败: ' + (data.msg || '未知错误'))
                }
            } catch (error) {
                console.log('卸载操作异常:', error.message)
                this.$message.error('卸载操作失败')
            } finally {
                this.operationLoading.unmount = false
            }
        },

        // 显示格式化确认对话框
        showFormatConfirm() {
            if (!this.sdCardInfo.isConnected) {
                this.$message.error('SD卡未连接')
                return
            }

            this.$confirm({
                title: '确认格式化SD卡',
                content: '格式化将删除SD卡上的所有数据，此操作不可逆。确定要继续吗？',
                okText: '确认格式化',
                okType: 'danger',
                cancelText: '取消',
                onOk: () => {
                    this.formatSdCard()
                },
                onCancel() {
                    console.log('取消格式化操作')
                }
            })
        },

        // 格式化SD卡
        async formatSdCard() {
            this.operationLoading.format = true
            try {
                this.$message.info('正在格式化SD卡，请稍候...')
                
                const response = await this.fetchWithTimeout(`http://${this.host}/mgmt/sd/format`, {
                    method: 'POST'
                })
                const data = await response.json()
                
                if (data.code === 0) {
                    this.$message.success('格式化成功')
                    await this.getSD() // 更新SD卡状态
                } else {
                    this.$message.error('格式化失败: ' + (data.msg || '未知错误'))
                }
            } catch (error) {
                if (error && error.message === 'timeout') {
                    this.$message.error('格式化超时')
                    this.sdCardInfo.status = 'timeout'
                } else {
                    this.$message.error('格式化请求异常')
                    this.sdCardInfo.status = 'unknown'
                }
                console.log('格式化操作异常:', error.message)
            } finally {
                this.operationLoading.format = false
            }
        }
    }
}
</script>

<style scoped>
.storage-management {
    display: flex;
    flex-direction: column;
    gap: 24px;
    max-width: 600px;
}

/* 状态卡片样式 */
.status-card .card-title {
    display: flex;
    align-items: center;
    gap: 8px;
}
.status-card .refresh-icon {
    cursor: pointer;
    font-size: 16px;
    color: #1890ff;
}
.status-card .refresh-icon:hover {
    color: #40a9ff;
}
.status-card .status-item {
    display: flex;
    align-items: center;
    justify-content: space-between;
}
.status-card .status-item .status-label {
    font-size: 14px;
    color: rgba(0, 0, 0, 0.85);
}

/* SD卡管理卡片样式 */
.sd-card-manager .card-title {
    display: flex;
    align-items: center;
    gap: 8px;
}
.sd-card-manager .refresh-icon {
    cursor: pointer;
    font-size: 16px;
    color: #1890ff;
}
.sd-card-manager .refresh-icon:hover {
    color: #40a9ff;
}
.sd-card-manager .capacity-section h4,
.sd-card-manager .operations-section h4 {
    margin-bottom: 16px;
    font-size: 14px;
    font-weight: 500;
    color: rgba(0, 0, 0, 0.85);
}
.sd-card-manager .capacity-info {
    padding: 16px;
    background-color: #fafafa;
    border-radius: 4px;
}
.sd-card-manager .capacity-details {
    margin-top: 12px;
}
.sd-card-manager .capacity-details p {
    margin: 4px 0;
    font-size: 14px;
}
.sd-card-manager .available-info {
    color: rgba(0, 0, 0, 0.45);
    font-size: 12px;
}
.sd-card-manager .operation-buttons {
    display: flex;
    flex-direction: column;
    gap: 12px;
}
.sd-card-manager .operation-btn {
    width: 100%;
    height: 36px;
    font-size: 14px;
}
.sd-card-manager .format-btn {
    margin-top: 8px;
}

/* 配置卡片样式 */
.config-card .unit {
    margin-left: 8px;
    color: rgba(0, 0, 0, 0.45);
    font-size: 14px;
}

/* 响应式设计 */
@media (max-width: 768px) {
    .storage-management {
        max-width: 100%;
    }
}
</style> 